from django.views.generic import DetailView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import HealthAnalysis
from django.shortcuts import get_object_or_404
from pets.models import Pet
import plotly.express as px
import pandas as pd
from django.http import JsonResponse


class PetHealthDashboard(LoginRequiredMixin, DetailView):
    model = Pet
    template_name = 'health/dashboard.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        pet = self.object

        # 确保用户只能访问自己的宠物
        if pet.owner != self.request.user:
            raise PermissionDenied

        # 获取健康分析
        analysis, created = HealthAnalysis.objects.get_or_create(pet=pet)
        if created or not analysis.last_analysis_date == timezone.now().date():
            analysis.analyze_health()

        context['analysis'] = analysis

        # 创建健康数据图表
        health_records = pet.health_records.order_by('date')
        if health_records:
            df = pd.DataFrame(list(health_records.values('date', 'weight', 'height', 'temperature')))
            df['date'] = pd.to_datetime(df['date'])

            # 体重趋势图
            weight_fig = px.line(df, x='date', y='weight', title='Weight Trend')
            weight_fig.update_layout(yaxis_title='Weight (kg)')
            context['weight_chart'] = weight_fig.to_html()

            # 多指标图表
            multi_fig = px.line(df, x='date', y=['weight', 'height'], title='Growth Metrics')
            multi_fig.update_layout(yaxis_title='Value')
            context['multi_metric_chart'] = multi_fig.to_html()

        return context


def health_risk_chart(request, pet_id):
    pet = get_object_or_404(Pet, id=pet_id, owner=request.user)
    analysis = HealthAnalysis.objects.get(pet=pet)

    risks = [
        {'name': 'Obesity', 'value': analysis.predicted_health_issues.get('obesity_risk', 0)},
        {'name': 'Dental Issues', 'value': analysis.predicted_health_issues.get('dental_issues', 0)},
        {'name': 'Joint Problems', 'value': analysis.predicted_health_issues.get('joint_problems', 0)}
    ]

    return JsonResponse({
        'health_score': analysis.health_score,
        'risks': risks
    })